package net.melon.plugin.core.result;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;

import org.apache.struts2.views.freemarker.FreemarkerManager;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;

/**
 * 默认使用WEB-INF路径下同相对路径的模板文件，如不存在，则使用编译目录下的模板文件
 * @author Administrator
 *
 */
public class UsageFreemarkerManager extends FreemarkerManager {
	
	private Configuration userConfiguration;
	
	private static final String WEB_INF_DIR = "WEB-INF"+File.separator;

	protected Configuration createUserConfiguration(ServletContext servletContext) throws TemplateException{
		userConfiguration =createConfiguration(servletContext);
		
		String realpath = servletContext.getRealPath("/");
		try {
			ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(),"/");
			FileTemplateLoader ftl = new FileTemplateLoader(new File(realpath+WEB_INF_DIR));
			MultiTemplateLoader mtl = new MultiTemplateLoader(new TemplateLoader[]{ctl,ftl});
			//userConfiguration.setDirectoryForTemplateLoading(new File(realpath+WEB_INF_DIR));
			userConfiguration.setTemplateLoader(mtl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return userConfiguration;
	}

	public Configuration getUserConfiguration(ServletContext servletContext) {
		if(userConfiguration==null){
			try {
				createUserConfiguration(servletContext);
			} catch (TemplateException e) {
				e.printStackTrace();
			}
		}
		return userConfiguration;
	}
}
